---
title: React
---

<Callout>
  如果你正在寻找使用 React 组件作为自定义组件的方法，请参阅[此处](/guides/sheets/ui/components#react)。
</Callout>

在集成 Univer 到 React 项目前，请确保你已经阅读了 [Univer 的安装和基本使用](/guides/sheets/getting-started/installation)章节以及了解 React 的基本概念和生命周期钩子。

## 在 React 18、19 中集成 Univer

### 集成步骤

1. 在 `useEffect` 中初始化 Univer
2. 在 `useEffect` 的清理函数中销毁 Univer

### 示例代码

```tsx
import { UniverSheetsCorePreset } from '@univerjs/preset-sheets-core'
import UniverPresetSheetsCoreZhCN from '@univerjs/preset-sheets-core/locales/zh-CN'
import { createUniver, LocaleType, mergeLocales } from '@univerjs/presets'
import { useEffect, useRef } from 'react'

import '@univerjs/preset-sheets-core/lib/index.css'

export function App() {
  const containerRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    const { univerAPI } = createUniver({
      locale: LocaleType.ZH_CN,
      locales: {
        [LocaleType.ZH_CN]: mergeLocales(
          UniverPresetSheetsCoreZhCN,
        ),
      },
      presets: [
        UniverSheetsCorePreset({
          container: containerRef.current,
        }),
      ],
    })

    univerAPI.createWorkbook({})

    return () => {
      univerAPI.dispose()
    }
  }, [])

  return (
    <div ref={containerRef} />
  )
}
```

## 在 React 16.9+、17 中集成 Univer

### 集成须知

#### 兼容性说明

Univer 的视图层基于 React 18.3.1 开发，但我们对 React 16.9+ 项目提供了最低限度的兼容性支持。请注意，这并不意味着会长期支持低版本 React，建议尽快升级到最新版以获得最佳体验和新特性。

#### 构建工具 alias 配置

在 React 16.9+ 环境下，需要通过构建工具的 alias 功能模拟 `react-dom/client` 的导出，否则部分功能无法正常使用。

**Vite 配置示例**

```typescript title="vite.config.ts"
export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: {
      'react-dom/client': path.resolve(__dirname, './src/client.ts'), // [!code ++]
    },
  },
})
```

```typescript title="src/client.ts"
import ReactDOM from 'react-dom'

export function createRoot(container: HTMLElement) {
  return {
    render: (element: JSX.Element) => {
      ReactDOM.render(element, container)
    },
  }
}
```

#### CDN/UMD 场景适配

如果你通过 `<script>` 标签引入 React 和 Univer，需要手动补充部分 API 以兼容新版接口，具体代码如下：

```html
<script>
  /**
   * With the support for React 19[^1], UMD users may need additional adaptation.
   *
   * [^1]: [support for React 19] https://github.com/dream-num/univer/pull/4247
   */

  /**
   * Fix `Uncaught TypeError: client.createRoot is not a function`
   * If using UMD React < 18, you might need the following code.
   */
  ;(function (global) {
    'use strict'
    if (!global.ReactDOM) {
      throw new Error('ReactDOM must be loaded before ReactCreateRoot.')
    }
    const ReactDOM = global.ReactDOM
    if (!ReactDOM.createRoot) {
      ReactDOM.createRoot = function (container) {
        return {
          render: (element) => {
            ReactDOM.render(element, container)
          },
        }
      }
    }
  })(this)

  /**
   * Fix `Uncaught TypeError: jsxRuntime.jsx is not a function`
   * If using UMD React, you might need the following code.
   * Reference: https://unpkg.com/react@18.3.1/cjs/react-jsx-runtime.production.min.js
   */
  ;(function (global) {
    'use strict'
    if (!global.React) {
      throw new Error('React must be loaded before ReactJSXRuntime.')
    }
    const React = global.React
    if (!React.jsx || !React.jsxs) {
      const REACT_ELEMENT_TYPE = Symbol.for('react.element')
      const hasOwnProperty = Object.prototype.hasOwnProperty
      const RESERVED_PROPS = {
        key: true,
        ref: true,
        __self: true,
        __source: true,
      }
      const ReactCurrentOwner = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner
      function createReactElement(type, config, maybeKey) {
        const props = {}
        let key = null
        let ref = null
        if (maybeKey !== undefined) {
          key = `${maybeKey}`
        }
        if (config.key !== undefined) {
          key = `${config.key}`
        }
        if (config.ref !== undefined) {
          ref = config.ref
        }
        for (var propName in config) {
          if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
            props[propName] = config[propName]
          }
        }
        if (type && type.defaultProps) {
          const defaultProps = type.defaultProps
          for (var propName in defaultProps) {
            if (props[propName] === undefined) {
              props[propName] = defaultProps[propName]
            }
          }
        }
        return {
          $$typeof: REACT_ELEMENT_TYPE,
          type,
          key,
          ref,
          props,
          _owner: ReactCurrentOwner.current,
        }
      }
      React.jsx = createReactElement
      React.jsxs = createReactElement
    }
  })(this)
</script>
```

### 集成步骤

1. 在 `useEffect` 中初始化 Univer
2. 在 `useEffect` 的清理函数中销毁 Univer

### 示例代码

```tsx
import { UniverSheetsCorePreset } from '@univerjs/preset-sheets-core'

import UniverPresetSheetsCoreZhCN from '@univerjs/preset-sheets-core/locales/zh-CN'
import { createUniver, LocaleType, mergeLocales } from '@univerjs/presets'
import { useEffect, useRef } from 'react'

import '@univerjs/preset-sheets-core/lib/index.css'

export function App() {
  const containerRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    const { univerAPI } = createUniver({
      locale: LocaleType.ZH_CN,
      locales: {
        [LocaleType.ZH_CN]: mergeLocales(
          UniverPresetSheetsCoreZhCN,
        ),
      },
      presets: [
        UniverSheetsCorePreset({
          container: containerRef.current,
        }),
      ],
    })

    univerAPI.createWorkbook({})

    return () => {
      univerAPI.dispose()
    }
  }, [])

  return (
    <div ref={containerRef} />
  )
}
```
